package com.cc.filemanagerlite

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.support.v4.app.Fragment
import android.support.v4.content.FileProvider
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.tbruyelle.rxpermissions2.RxPermissions
import java.io.File
import java.lang.Exception

/**
 * Created by YuanChao on 18-12-12.
 */
class FileListFragment : Fragment() {
    lateinit var swipeRefreshLayou: SwipeRefreshLayout
    lateinit var recyclerView: RecyclerView
    var file = File("")
    lateinit var mAdapter: BaseQuickAdapter<File, BaseViewHolder>
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_file_list, container, false)
    }

    @SuppressLint("CheckResult")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        swipeRefreshLayou = view.findViewById(R.id.srl)
        swipeRefreshLayou.isEnabled = false;
        recyclerView = view.findViewById(R.id.rv)
        RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .subscribe {
                if (!it) {
                    Toast.makeText(context, "请打开存储权限", Toast.LENGTH_SHORT).show()
                } else {
                    getData()
                    swipeRefreshLayou.isEnabled = true
                    swipeRefreshLayou.setOnRefreshListener {
                        swipeRefreshLayou.isRefreshing = false
                        getData()
                    }
                }
            }
    }

    private fun getData() {

        val path: String? = activity?.intent?.getStringExtra("path")
        file = if (TextUtils.isEmpty(path)) Environment.getExternalStorageDirectory() else
            File(path)

        val files = ArrayList<File>()
        for (f in file.listFiles()) {
            files.add(f)
        }
        mAdapter = object :
            BaseQuickAdapter<File, BaseViewHolder>(android.R.layout.simple_list_item_1, files) {
            val padding = resources.getDimensionPixelOffset(R.dimen.mid)
            override fun convert(helper: BaseViewHolder, item: File) {
                val tv = helper.itemView as TextView;
                helper.itemView.background = resources.getDrawable(R.drawable.item_bg)
                tv.setText(item.name)
                tv.compoundDrawablePadding = padding
                tv.setCompoundDrawablesRelativeWithIntrinsicBounds(
                    if (item.isDirectory) R.drawable.ic_folder_black_24dp else R.drawable.ic_file,
                    0,
                    0,
                    0
                )
            }
        }
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = mAdapter
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val file = mAdapter.getItem(position)
            if (file?.isDirectory!!)
                FileLisetActivity.into(context, this@FileListFragment.mAdapter.getItem(position)?.path)
            else {
                show(file.path)
            }
        }
    }

    fun show(path: String) {
        try {
            val intent = Intent()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                val contentUri =
                    context?.let { FileProvider.getUriForFile(it, "com.cc.filemanagerlite.fileProvider", File(path)) }
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.setDataAndType(contentUri, "*/*")
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.setDataAndType(Uri.fromFile(file), "*/*")
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace();
        }
    }

}
